<template>
  <!-- 消防演习编辑/新增 -->
  <el-row class="fire-drill-info-form" type="flex" justify="center" v-loading="loading">
    <el-col>
      <el-form
        label-width="150px"
        :model="baseInfoForm"
        :rules="baseInfoFormRules"
        ref="baseInfoForm"
        @submit.native.prevent
      >
        <el-form-item label="标题：" prop="title">
          <el-input v-model="baseInfoForm.title" auto-complete="off" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="参演单位：" prop="orgIds">
          <el-select
            clearable
            filterable
            multiple
            v-model="baseInfoForm.orgIds"
            @change="orgChange"
            placeholder="请选择参演单位"
          >
            <el-option
              v-for="item in orgList"
              :key="String(item.organizationId)"
              :label="item.shortName"
              :value="String(item.organizationId)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="演习时间：" prop="time">
          <el-date-picker
            v-model="baseInfoForm.time"
            type="datetimerange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="演习预案：" prop="planId">
          <el-select filterable v-model="baseInfoForm.planId" placeholder="请选择演习预案">
            <el-option v-for="item in planIdOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="正文：" prop="content">
          <quill-editor
            style="width:100%"
            ref="myQuillEditor"
            v-model="baseInfoForm.content"
            :options="utils.intEditorOptions()"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
          ></quill-editor>
          <!-- 文件上传input 将它隐藏-->
          <el-upload
            :action="QINIUUPLOADURL"
            :before-upload="beforeAvatarUploadEditor"
            :data="qiniuDataEditor"
            :on-success="handleAvatarSuccessEditor"
            ref="uploadEditor"
            style="display:none"
          >
            <el-button size="small" type="primary" id="imgInput">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="封面：" prop="pictures">
          <el-upload
            :action="QINIUUPLOADURL"
            :multiple="false"
            ref="upload"
            list-type="picture-card"
            :data="coverPicQiniuData"
            :on-success="function(res, file, fileList) {return handleAvatarSuccess(res, file, fileList, 'coverPicQiniuData')}"
            :on-remove="function(file, fileList) {return handleRemovePic(file, fileList, 'coverPicQiniuData')}"
            :on-error="function(res) {return handleError(res, 'coverPicQiniuData')}"
            :before-upload="function(file){return beforeAvatarUpload(file, 'coverPicQiniuData')}"
            :on-preview="$imgPreview"
            :file-list="coverPicQiniuData.fileList"
            :limit="1"
            :on-exceed="function(files, fileList) {return handleExceed(files, fileList, 'coverPicQiniuData')}"
            accept="image/gif, image/jpeg, image/jpg, image/bmp, image/png"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button @click.stop="closeFun" round>取消</el-button>
          <el-button type="primary" @click="saveFireDrillInfo('baseInfoForm')" round>保存</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<script>
import utils from '@/utils/util'
import { getOrgList } from '@/api/org'
import { selectEmergencyPlanInfo } from '@/api/plan'
import { qnToken } from '@/api/api'
import { saveDrillRecord } from '@/api/emergencyPlan'

let TYPEMAP = {
  coverPicQiniuData: '封面图片',
}
export default {
  name: 'FireDrillInfoFrom',
  props: {
    closeFun: {
      required: true,
      type: Function,
    },
    oldInfo: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      utils: utils,
      loading: false,
      // 上传图片携带的默认参数
      qiniuDefaultData: {
        token: '',
      },
      orgList: [], // 参演单位下拉框选项
      planIdOptions: [], // 应急预案下拉框选项
      baseInfoForm: {
        title: '',
        orgIds: [],
        time: '',
        planId: '', // 预案id
        content: '',
      },
      baseInfoFormRules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        orgIds: [
          { required: true, message: '请选择参演单位', trigger: 'blur' },
        ],
        time: [
          { required: true, message: '请设置演习时间', trigger: 'change' },
        ],
        planId: [
          { required: true, message: '请选择演习预案', trigger: 'change' },
        ],
        content: [{ required: true, message: '请输入正文', trigger: 'change' }],
      },
      // 富文本编辑器上传
      qiniuDataEditor: {
        key: '',
        fileList: [],
      },
      // 封面图片
      coverPicQiniuData: {
        key: '',
        fileList: [],
      },
    }
  },
  created() {
    let that = this
    that.getOrgOptions()
    //上传之前获取 token
    qnToken({}).then((res) => {
      that.qiniuDefaultData.token = res.data
      $.extend(that.qiniuDataEditor, that.qiniuDefaultData)
      $.extend(that.coverPicQiniuData, that.qiniuDefaultData)
      that.$nextTick(() => {
        // 如果有历史数据
        if (Object.keys(that.oldInfo).length > 0) {
          for (var key in that.baseInfoForm) {
            if (key == 'time') {
              let arr = []
              arr.push(that.oldInfo.startTime)
              arr.push(that.oldInfo.endTime)
              that.baseInfoForm[key] = arr
            } else if (key == 'orgIds') {
              that.baseInfoForm[key] = that.oldInfo.orgIds.split(',')
            } else {
              that.baseInfoForm[key] = that.oldInfo[key]
            }
          }
          that.getPlanIdOptions()
          // 设置封面图片回显
          that.oldInfo.coverPic
            ? $.each(that.oldInfo.coverPic.split(','), (index, url) => {
                let arr = url.split('/')
                that.coverPicQiniuData.fileList.push({
                  name: arr[arr.length - 1],
                  url: url,
                })
              })
            : ''
        } else {
          // 新增时，如果是单单位用户默认选中单位
          if (!this.$store.state.userinfo.isMuilUnitUser) {
            that.baseInfoForm.orgIds = String(
              this.$store.state.userinfo.org.id
            ).split(',')
            this.getPlanIdOptions()
          }
        }
      })
    })
  },
  mounted() {
    // 为图片ICON绑定事件  getModule 为编辑器的内部属性
    this.$refs.myQuillEditor.quill
      .getModule('toolbar')
      .addHandler('image', this.imgHandler)
    this.$refs.myQuillEditor.quill
      .getModule('toolbar')
      .addHandler('video', this.videoHandler) // 为视频ICON绑定事件
  },
  methods: {
    // 获取业主单位
    getOrgOptions() {
      // 获取业主单位信息
      getOrgList({
        queryType: 0,
      }).then((res) => {
        if (res.status === 200) {
          this.orgList = res.data
          this.$nextTick(() => {
            this.baseInfoFormRules.orgIds[0].trigger = 'change'
          })
        }
      })
    },
    // 获取应急预案
    getPlanIdOptions() {
      selectEmergencyPlanInfo({
        orgIds: this.baseInfoForm.orgIds,
        planName: '',
        pageSize: 100,
        pageIndex: 0,
      }).then((res) => {
        if (res.status === 200) {
          this.planIdOptions = res.data
        }
      })
    },
    orgChange() {
      this.getPlanIdOptions()
    },
    //--------------------BEGIN  富文本编辑器相关------------------------------//
    beforeAvatarUploadEditor: function (file) {
      //重命名和校验
      this.loading = true
      const suffix = file.name.split('.')
      const ext = suffix.splice(suffix.length - 1, 1)[0]
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      this.qiniuDataEditor.key = 'ilink_' + new Date().getTime() + fielType
    },
    handleAvatarSuccessEditor: function (res, file, fileList) {
      //上传成功
      this.loading = false
      let vm = this
      let url = QINIUUPLOADURL.indexOf('uploadFile')>-1? res.data:QINIUPATH+res.key
      if (url != null && url.length > 0) {
        // 将文件上传后的URL地址插入到编辑器文本中
        let value = url
        vm.qiniuDataEditor.fileList = vm.$refs.myQuillEditor.quill.getSelection()
        vm.$refs.myQuillEditor.quill.insertEmbed(
          vm.qiniuDataEditor.fileList !== null
            ? vm.qiniuDataEditor.fileList.index
            : 0,
          vm.uploadType,
          value
        ) // 调用编辑器的 insertEmbed 方法，插入URL
      } else {
        this.$message.error('上传失败')
      }
      this.$refs['uploadEditor'].clearFiles() // 插入成功后清除input的内容
    },
    // 点击图片ICON触发事件
    imgHandler(state) {
      this.addRange = this.$refs.myQuillEditor.quill.getSelection()
      if (state) {
        let fileInput = document.getElementById('imgInput')
        fileInput.click() // 加一个触发事件
      }
      this.uploadType = 'image'
    },
    // 点击视频ICON触发事件
    videoHandler(state) {
      this.addRange = this.$refs.myQuillEditor.quill.getSelection()
      if (state) {
        let fileInput = document.getElementById('imgInput')
        fileInput.click() // 加一个触发事件
      }
      this.uploadType = 'video'
    },
    // 编辑器光标离开 将编辑器内容发射给父组件
    onEditorBlur(editor) {
      //时长 = 视频长度 + 总字数/500 * 60（秒）+ 图片的时长(推荐学习时长算法)
      let str = '<img src='
      let html = this.baseInfoForm.content //this.editForm.text
      let n = html.split(str).length - 1 //添加图片的张数
      let picTime = 0
      let text = editor.getText()

      if (this.PicOld != n) {
        if (n < 10) {
          this.PicTime = this.firstPic
          this.firstPic--
          this.PicOld = n
          this.learnTime = this.learnTime + this.PicTime / 60
        } else {
          this.PicTime = 3
          this.PicOld = n
          this.learnTime = this.learnTime + this.PicTime / 60
        }
      }
      if (text.length - 1) {
        let a = (text.length - 1 - this.oldtext) / 500
        this.learnTime = this.learnTime + a
        this.oldtext = text.length - 1
      }
    },
    // 编辑器获得光标
    onEditorFocus(editor) {
      editor.enable(true) // 实现达到上限字符可删除
    },
    // 编辑器文本发生变化
    onEditorChange({ editor, html, text }) {
      let textLength = text.length
      // if (textLength > 10000) {
      //     this.$message.error('最多输入10000个字符');
      //     editor.enable(false)
      // }
    },
    // 清除编辑器内容
    callMethod() {
      this.baseInfoForm.content = ''
    },
    //--------------------END  富文本编辑器相关------------------------------//
    //--------------------START  封面上传相关------------------------------//
    // 重命名和校验
    beforeAvatarUpload(file, type, obj) {
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      if (obj) {
        obj[type].key = fielLocalName + '_' + new Date().getTime() + fielType
      } else {
        this[type].key = fielLocalName + '_' + new Date().getTime() + fielType
      }
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isLt20M) {
        this.$message.error('封面图片大小不能超过 20MB!')
        return false
      }
    },
    // 上传成功
    handleAvatarSuccess(res, file, fileList, type, obj) {
      if (obj) {
        obj[type].fileList = fileList
      } else {
        this[type].fileList = fileList
      }
    },
    // 删除成功
    handleRemovePic(file, fileList, type, obj) {
      if (obj) {
        obj[type].fileList = fileList
      } else {
        this[type].fileList = fileList
      }
    },
    handleError(res, type) {
      this.$message({
        message: `${TYPEMAP[type]}上传失败`,
        duration: 2000,
        type: 'warning',
      })
    },
    handleExceed(files, fileList, type) {
      this.$message.warning(
        `${TYPEMAP[type]}最多只能上传1张，如需重新上传请先删除原先图片`
      )
    },
    //--------------------END  封面上传相关------------------------------//
    // 保存
    saveFireDrillInfo(formName) {
      let that = this
      // 校验表单
      that.$refs[formName].validate((valid) => {
        if (valid) {
          let parames = {
            id: that.oldInfo.id || '',
            title: that.baseInfoForm.title,
            orgIds: that.baseInfoForm.orgIds.join(','),
            startTimeStr: that.baseInfoForm.time
              ? that.baseInfoForm.time[0]
              : '',
            endTimeStr: that.baseInfoForm.time ? that.baseInfoForm.time[1] : '',
            planId: that.baseInfoForm.planId,
            content: that.baseInfoForm.content,
            coverPic: utils.ilinkArrHandle
              .getqiniuPicUrlArr(that.coverPicQiniuData.fileList)
              .toString(),
            updateAccount: that.$store.state.userinfo.accountName,
          }
          saveDrillRecord(parames).then((res) => {
            if (res.status === 200) {
              that.$message({
                message: '保存成功！',
                type: 'success',
              })
              that.closeFun(true)
            }
          })
        } else {
        }
      })
    },
  },
}
</script>